#include <io.h>
#include <string>
#include <iostream>
#include <fstream>

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"

#define JSON_FILE_MAX_SIZE 65536 //64KB

namespace ICE
{
    char* loadFile(const std::string &file, std::streamoff &size)
    {
        std::ifstream fs(file.c_str(), std::ios::binary);
        if(!fs.is_open())
            throw std::runtime_error(file + " was not found!");
        fs.seekg(0, std::ios::end);
        size = fs.tellg();
        char *data = new char[size + 1];
        fs.seekg(0);
        fs.read(data, size);
        fs.close();
        return data;
    }

    bool writeFile(const std::string &filePath,const std::string &srcStr)
    {
        FILE* pFile;
        pFile=fopen(filePath.c_str(),"w");
        if(pFile==nullptr)
            return false;
        
        fputs(srcStr.c_str(),pFile);
        fclose(pFile);
        return true;
    }

    bool writeJOSNFile(rapidjson::Document& d,const std::string& filePath)
    {
        rapidjson::StringBuffer buffer;
        rapidjson::PrettyWriter<rapidjson::StringBuffer> prettyWriter(buffer);
        d.Accept(prettyWriter);
        prettyWriter.SetIndent('\t',4);

        if(!writeFile(filePath,buffer.GetString()))
        {
            std::cout<<"writefile failed!"<<std::endl;
            return false;
        }

        return true;
    }

    void readJOSNFile(const std::string& filePath,rapidjson::Document& doc)
    {
        FILE* fp=fopen(filePath.c_str(),"rb");
        char readBuffer[JSON_FILE_MAX_SIZE];
        rapidjson::FileReadStream inputStream(fp,readBuffer,JSON_FILE_MAX_SIZE);

        rapidjson::Document d;
        doc.ParseStream(inputStream);
    }
}